import os
import cv2
from flask import Flask, flash, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
#### 安装库:opencv-python和opencv-contrib-python、numpy、matplotlib
app = Flask(__name__)
app.secret_key = os.urandom(24)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['UPLOAD_FOLDER']=os.path.join(basedir,"upload")
# 上传文件并重定向用户到上传后的文件URL
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 检查请求中是否包含文件部分
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # 如果用户没有选择文件，浏览器也会提交一个没有文件名的空文件
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        filename = secure_filename(file.filename)
        path=app.config['UPLOAD_FOLDER'] #存储的路径
        fullpath=os.path.join(path, filename)# 文件全路径
        file.save(fullpath)
        print(fullpath)
        return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

# 提供已上传文件的下载链接
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    fn1 = zishiying(filename)  # 进行均衡化
    return send_from_directory(app.config['UPLOAD_FOLDER'], fn1)

def zishiying(imgName):
    print("处理函数中的传入文件名：：：", imgName)
    import cv2 as cv
    # 1. 以灰度图形式读取图像
    readFilename=os.path.join(app.config['UPLOAD_FOLDER'],imgName)
    print("处理函数中imread前：：：",readFilename)
    img = cv.imread(readFilename, 0)
    print("处理函数中imread后：：：",img)
    # 2. 创建一个自适应均衡化的对象，并应用于图像
    clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    cl1 = clahe.apply(img)
    print(cl1)
    name="chuli"+imgName
    fullname=os.path.join(app.config['UPLOAD_FOLDER'],name)
    print("处理函数中的：：：",fullname)
    cv2.imwrite(fullname,cl1)
    return name






if __name__ == '__main__':
    app.run(debug=True)